import router from './router'
import { getToken } from '@/store/localStorage/cookies' // get token from cookie
import { GetLoginStatus } from '@/axios/authorize'

() => this.$Loading.config({
  color: '#5cb85c',
  failedColor: '#f0ad4e',
  height: 5
})

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  /* has token*/
  // start progress bar
  () => this.$Loading.start()
  
  // set page title
  document.title = '浙江祥生建设工程有限公司'

  // determine whether the user has logged in

  let hasToken = getToken();
  let loginstatus = false;

  GetLoginStatus().then(res => {
    loginstatus = (res===1);
    if (hasToken && loginstatus) {
      if (to.path === '/login') {
        next('/');
        () => this.$Loading.finish(); 
      } else {
        () => this.$Loading.finish(); 
      }
      next();
    } else {
      /* has no token*/
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`);
        () => this.$Loading.finish();
      }
    }
  })
})

router.afterEach(() => {
  // finish progress bar
  () => this.$Loading.finish()
})
